﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Globalization;
using System.Reflection;

namespace Senthil.Mobile.WhereAmI
{
    public static class CrashHandler
    {
        static string appDataDirectory = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
        public static void HandleCrash(string applicationName, Exception e)
        {
            string dir = Path.Combine(appDataDirectory, applicationName);

            if (!Directory.Exists(dir))
                Directory.CreateDirectory(dir);

            string fileName = Path.Combine(dir, GetFileNameBasedOnDateTime());
            
            using (StreamWriter wr = new StreamWriter(fileName))
            {
                wr.WriteLine(e.ToString());
                wr.WriteLine(Assembly.GetCallingAssembly().FullName, Assembly.GetCallingAssembly().GetName().Version.ToString());
                wr.WriteLine(Assembly.GetExecutingAssembly().FullName, Assembly.GetExecutingAssembly().GetName().Version.ToString());
            }

            string textToShow = string.Format("{0}. The crash log has been saved at {1}. Help improve {2} by sending the log to {3}",
                e.Message, fileName, applicationName, "senthil.thecoder@gmail.com");

            MessageBox.Show(textToShow, applicationName + " crashed", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
        }

        private static string GetFileNameBasedOnDateTime()
        {
            return string.Format(CultureInfo.CurrentCulture, "CrashLog-{0}.txt", DateTime.Now.ToString("dd-MM-yy HH-mm-ss"));
        }
    }
}
